package com.woniuxy.oa.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.woniuxy.oa.entity.Approval;
import com.woniuxy.oa.entity.Employee;
import com.woniuxy.oa.entity.Employee_Holiday;
import com.woniuxy.oa.entity.Holiday;
import com.woniuxy.oa.entity.HolidayType;
import com.woniuxy.oa.enums.ApprovalApplyType;
import com.woniuxy.oa.exception.ApprovalException;
import com.woniuxy.oa.exception.HolidayException;
import com.woniuxy.oa.service.HolidayService;
import com.woniuxy.oa.utils.ApprovalUtil;

@RequestMapping("/holiday")
@Controller
public class HolidayController {


	@Autowired
	HolidayService holidayService;

	public void setHolidayService(HolidayService holidayService) {
		this.holidayService = holidayService;
	}
	@ResponseBody
	//获取请假类型相关信息
	@RequestMapping("/getHType")
	public List<HolidayType> getHtype(){
		System.out.println("获取请假类型方法被访问");
		List<HolidayType> hTypes = null;
		try {
			hTypes = holidayService.getHolidayType();
			return hTypes;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}	
	}
	
	//修改方法
	@Transactional(rollbackFor = { RuntimeException.class, Error.class, Exception.class })
	@ResponseBody
	@RequestMapping("/modifyHoliday")
	public List<String> modifyHoliday(Approval approval,Holiday holiday,HttpServletRequest request) {
		List<String> msg = new ArrayList<String>();
		System.out.println("修改方法被访问");
		System.out.println("修改方法被访问"+approval);
		System.out.println("修改方法被访问"+holiday);
		try {
			//非空验证
			if(approval == null||approval.getA_eid()==null||holiday==null||holiday.getH_id()==null||holiday.getHt_id()==null
					||holiday.getStarttime()==null||holiday.getEndtime()==null||holiday.getReason()==null) {
				msg.add("参数不能为空！");
				throw new HolidayException();
			}
			//检查发过来的holiday是否是已存在的，不存在直接抛异常
			Holiday selectHoliday = holidayService.selectHolidayByHid(holiday.getH_id());
			if(selectHoliday==null) {
				msg.add("该假期不存在");
				throw new HolidayException();
			}
			//检查发过来的信息是否和查出来的信息一致
			if(checkModifyInfo(approval,holiday,selectHoliday)) {
				msg.add("信息一致，不需要修改");
				throw new HolidayException();
			}
			//时间检查，检查日期是否开始小于结束且间隔大于一个小时
			if(!checkTime(holiday.getStarttime(),holiday.getEndtime())) {
				throw new ApprovalException("时间参数不正确！");
			}
			
			Employee emp = (Employee) request.getSession().getAttribute("user");
			
			//检查发过来的holiday对应的发起人是否为当前用户
//			if((holidayService.selectApprovalByAid(selectHoliday.getA_id()).getE_id())!=(emp.getId())) {
//				throw new HolidayException("操作用户不正确");
//			}
			
			//修改假期
			holidayService.updateHoliday(holiday,selectHoliday.getA_id());
			//修改审批关系
			holidayService.updateApprovalAeid(approval.getA_eid(), holiday.getA_id());
			msg.add("修改成功");
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
//			msg.add("修改失败");
			return msg;
		}
	}
	
	//检查修改信息
	private boolean checkModifyInfo(Approval approval, Holiday holiday, Holiday selectHoliday) {
		boolean isOk=false;
		String reason = selectHoliday.getReason();
		
		String reason2 = holiday.getReason();
		String endtime = selectHoliday.getEndtime();
		String endtime2 = holiday.getEndtime();
		String starttime = selectHoliday.getStarttime();
		String starttime2 = holiday.getStarttime();
		Integer ht_id = selectHoliday.getHt_id();
		Integer ht_id2 = holiday.getHt_id();
		Integer h_id = selectHoliday.getH_id();
		Integer h_id2 = holiday.getH_id();
		Integer a_eid = holidayService.selectApprovalByAid(selectHoliday.getA_id()).getA_eid();
		Integer a_eid2 = approval.getA_eid();
		System.out.println("原a_eid:"+a_eid+"传过来的a_eid："+a_eid2);
		System.out.println("a_eid比较结果"+(a_eid2==a_eid));
		
		System.out.println("原h_id:"+h_id+"传过来的h_id2："+h_id2);
		System.out.println("h_id比较结果"+(h_id2==h_id));
		
		System.out.println("原ht_id:"+ht_id+"传过来的ht_id2："+ht_id2);
		System.out.println("ht_id比较结果"+(ht_id2==ht_id));
		
		System.out.println("原starttime:"+starttime+"传过来的starttime2："+starttime2);
		System.out.println("starttime比较结果"+(starttime2.equals(starttime)));
		
		System.out.println("原endtime:"+endtime+"传过来的endtime2："+endtime2);
		System.out.println("endtime比较结果"+(endtime2.equals(endtime)));
		
		System.out.println("原reason:"+reason+"传过来的reason2："+reason2);
		System.out.println("reason比较结果"+(reason2==reason));
		if(a_eid2==a_eid&&
				h_id2==h_id&&ht_id2==ht_id
				&&starttime2.equals(starttime)&&endtime2.equals(endtime)
				&&reason2.equals(reason)) {
			
			
			isOk=true;
		}
		System.out.println("isok:"+isOk);
		return isOk;
	}
	@ResponseBody
	//删除假期的方法，实质是将flag改为1
	//需要验证 要删除的审批 中发起人是否是当前用户
	@RequestMapping("/deleteHoliday")
	public List<String> deleteHoliday(HttpServletRequest request) {
		List<String> msg = new ArrayList<String>();
		try {
			//检查该审批申请中的发起人是否是当前用户
			Employee emp = (Employee) request.getSession().getAttribute("user");
			//获取发过来的a_id
			Integer a_id = Integer.parseInt(request.getParameter("a_id"));
			//根据审批号查到发起人id
			Integer e_id = holidayService.getIdByAid(a_id);
			System.out.println("收到的a_id为："+a_id);
			//这里先去掉，以后有user了就加上
//			if(emp.getId()==a_id) {
			holidayService.deleteHolidayByAid(a_id);
//			}
			msg.add("删除成功");
			return msg;
//			throw new ApprovalException("删除失败");
		} catch (Exception e) {
			e.printStackTrace();
			msg.add("删除失败");
			return msg;
		}
	}
	

	// 先后操作多个表，使用事务
	@Transactional(rollbackFor = { RuntimeException.class, Error.class, Exception.class })
	@RequestMapping("/createHolidayApply")
	public String createVactionApply(Model model, HttpServletRequest request, Holiday holiday) {
		try {
			//获取指定的审批人id
			String parameter = request.getParameter("a_eid");
			if (parameter == null || holiday == null || holiday.getHt_id() == null || holiday.getStarttime() == null
					|| holiday.getEndtime() == null || holiday.getReason() == null) {
				throw new ApprovalException("别搞服务器");
			}
			Integer a_eid = Integer.parseInt(parameter);
			System.out.println("准备创建一个假期申请，获得前端传过来的审批人id为" + a_eid);
			HttpSession session = request.getSession();
			//检查审批人id
			List<Employee> approvalPersons = (List<Employee>) session.getAttribute("approvalPersons");
			if (approvalPersons == null) {
				throw new ApprovalException("未获取到保存的审批人！");
			}
			List<Integer> ids = new ArrayList<Integer>();
			for (Employee employee : approvalPersons) {
				if (employee.getId() <= 0) {
					throw new ApprovalException("没有获取到保存的审批人id");
				}
				ids.add(employee.getId());
			}
			// 检查审批人是否ojbk
			if (!ids.contains(a_eid)) {
				throw new ApprovalException("不要瞎几把传参数");
			}
			// 检查请假类型
			if (holiday.getHt_id() <= 0 || holiday.getHt_id() > 9) {
				throw new ApprovalException("请假类型不正确！");
			}
			// 检查请假时间，
			if(!checkTime(holiday.getStarttime(),holiday.getEndtime())) {
				throw new ApprovalException("时间参数不正确！");
			}
			
			
			
			// 当前用户id,从session域中获取,假装自己做了登录
			Employee employee = (Employee) session.getAttribute("user");
//			Integer e_id = employee.getId();
			Integer e_id=9;
			
			//请假期间不能再请假，从员工-请假表读到已审批的请假记录，获取现在的时间，看看是否在查出来的信息的开始和结束时间内
			if(holidayService.getExaminedRecord(9,ApprovalUtil.getNow())!=null) {
				throw new ApprovalException("你已经处于假期了！");
			}
			
			
			//插入审批表返回一个审批号
			Integer a_id = ApprovalUtil.addApprovalGetId(request, a_eid, ApprovalApplyType.HOLIDAY);
			System.out.println("已经向审批表插入数据，获得返回的审批号为"+a_id);

			/*
			 * 调用向假期表插入假期信息的方法 需要审批号、请假类型、开始时间，结束时间、请假原因
			 * 
			 */
			holiday.setA_id(a_id);
			Integer h_id = holidayService.addHolidayGetId(holiday);
			System.out.println("已经向假期表插入数据，获得返回的假期号为"+h_id);

			// 向员工、假期表写入关系,需要写入 员工id,h_id
			Employee_Holiday employee_Holiday = new Employee_Holiday(null, e_id, h_id);
			Integer addEmp_holiday = holidayService.addEmp_holiday(employee_Holiday);
			System.out.println("已经向员工--假期关系表插入数据，获得返回的关系号为"+addEmp_holiday);
			if(addEmp_holiday>0) {
				return "redirect:/leave.html";
			}
			throw new HolidayException("创建请假申请失败");
		} catch (ApprovalException e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "forward:/errorss.html";
		}

	}
	
	//检查时间的方法
	private boolean checkTime(String starttime, String endtime) {
		boolean isOk = false;
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date dt1 = df.parse(starttime);
            Date dt2 = df.parse(endtime);
            long time = dt1.getTime();
            long time2 = dt2.getTime();
            long intervalTime  =  time2-time;
            if(time<time2 && intervalTime>(60*60*1000)) {
            	isOk=true;
            	System.out.println("时间参数正确");
            }else {
            	System.out.println("时间参数错误");
            	throw new HolidayException("时间参数错误");
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
            
		return isOk;
	}
}
